<template>
  <view class="container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <input 
        class="search-input" 
        placeholder="搜索台球馆"
        v-model="searchText"
        @input="handleSearch"
      />
    </view>

    <!-- 台球馆卡片列表 -->
    <view class="pool-hall-list">
      <view 
        class="pool-hall-card" 
        v-for="(hall, index) in filteredHalls" 
        :key="index"
      >
        <swiper class="hall-swiper" :autoplay="true" :indicator-dots="true" circular>
  <swiper-item v-for="(img, i) in hall.images" :key="i" @click="previewImage(hall.images, i)">
    <image :src="img" class="hall-image" mode="widthFix"></image>
  </swiper-item>
</swiper>
        <view class="hall-name">{{ hall.name }} ⌖ {{ hall.distance }}</view>
        <view class="hall-address">{{ hall.address }}</view>
        <view class="hall-status">
          <text class="status-dot" :class="{ 'open': hall.isOpen, 'closed': !hall.isOpen }"></text>
          {{ hall.isOpen ? '营业中' : '已打烊' }} | 空闲桌：
          <text :class="{ 'available': hall.availableTables > 0, 'full': hall.availableTables <= 0 }">
            {{ hall.availableTables }}/{{ hall.totalTables }}
          </text>
        </view>
        <view class="action-buttons">
          <button class="nav-btn" @click="navigateToHall(hall)">导航</button>
          <button class="book-btn" @click="bookTable(hall)">预约</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchText: '',
      poolHalls: process.env.NODE_ENV === 'development' ? [
{
name: '星火台球俱乐部',
distance: '1.2km',
isOpen: true,
availableTables: 12,
totalTables: 16,
images: [
'/static/pool_hall1.jpg',
'/static/台球桌.jpg',
'/static/pool_hall2.jpg'
],
address: '绥江县凤仪路8号1-3',
latitude: 30.449006,
longitude: 115.746757,
},
{
name: '绥江县伯爵台球俱乐部',
distance: '0.8km',
isOpen: true,
availableTables: 5,
totalTables: 10,
images: [
'/static/pool_hall2.jpg',
'/static/台球桌.jpg',
'/static/pool_hall3.jpg'
],
address: '绥江县龙行大道13号新世纪商贸广场',
latitude: 39.915,
longitude: 116.404,
},
{
name: '壹号台球',
distance: '2.1km',
isOpen: false,
availableTables: 0,
totalTables: 8,
images: [
'/static/pool_hall3.jpg',
'/static/台球桌.jpg',
'/static/pool_hall1.jpg'
],
address: '绥江县龙行大道（东段）21号4栋1-5铺',
latitude: 30.663988,
longitude: 104.073215,
}
] : [],
      currentPage: 1,
      pageSize: 4,
      total: 0,
      loading: false,
      noMore: false,
      reachedBottomOnce: false
    }
  },
  computed: {
    filteredHalls() {
      return this.poolHalls
        .filter(hall => hall.name.toLowerCase().includes(this.searchText.toLowerCase()) && hall.status !== 0)
        .sort((a, b) => {
          const distanceA = parseFloat(a.distance.replace('km', ''));
          const distanceB = parseFloat(b.distance.replace('km', ''));
          return distanceA - distanceB;
        });
    }
  },
  onLoad() {
    this.loadData()
  },
  onReachBottom() {
    if (!this.noMore) {
      this.currentPage++
      this.loadData()
    } else if (this.reachedBottomOnce) {
      uni.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
      this.reachedBottomOnce = false;
    } else {
      this.reachedBottomOnce = true;
    }
  },
  onShow() {
    // 页面显示时刷新数据，确保从预约页返回时数据是最新的
    this.refreshHallDataFromStorage();
  },
  methods: {
    previewImage(images, index) {
      uni.previewImage({
        current: index,
        urls: images
      });
    },
    handleSearch() {
      // 搜索逻辑已在computed中处理
      // 添加防抖处理
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.$forceUpdate();
      }, 300);
    },
    navigateToHall(hall) {
      uni.navigateTo({
        url: '/pages/map/map?hall=' + encodeURIComponent(JSON.stringify(hall))
      })
    },
    bookTable(hall) {
      // 跳转到预约页面
      uni.navigateTo({
        url: '/pages/appointment/appointment?hall=' + encodeURIComponent(JSON.stringify({
          ...hall,
          tables: Array.from({length: hall.totalTables}, (_, i) => ({
            number: `${i+1}号桌`,
            status: i < hall.availableTables ? 'available' : 'occupied'
          }))
        }))
      })
    },
    async loadData(callback) {
      if (this.loading) return
      this.loading = true
      try {
        // 使用本地模拟数据
        // 模拟分页加载更多数据
        const mockItemsPerPage = 3; // 与初始数据量一致或根据需要调整
        const totalMockItems = 9; // 设定一个大于初始加载量的总数
        let currentMockBatch = [];

        if (process.env.NODE_ENV === 'development') {
          const startIndex = (this.currentPage - 1) * mockItemsPerPage;
          // 简单模拟，实际应用中可能需要更复杂的逻辑生成不同数据
          for (let i = 0; i < mockItemsPerPage; i++) {
            const itemIndex = startIndex + i;
            if (itemIndex < totalMockItems) { // 确保不超过总数
              currentMockBatch.push({
                id: `hall_mock_${itemIndex + 1}`,
                name: `模拟台球馆 ${itemIndex + 1}`,
                distance: `${(Math.random() * 5).toFixed(1)}km`,
                isOpen: Math.random() > 0.2, // 80% 概率营业中
                availableTables: Math.floor(Math.random() * 10),
                totalTables: 10 + Math.floor(Math.random() * 10),
                imageUrl: `/static/pool_hall${(itemIndex % 3) + 1}.jpg`, // 循环使用图片
                address: `模拟地址 ${itemIndex + 1}`,
                status: 1,
                latitude: 28.596 + Math.random() * 0.1,
                longitude: 104.833 + Math.random() * 0.1,
              });
            }
          }
        }

        let data = {
          list: currentMockBatch,
          total: process.env.NODE_ENV === 'development' ? totalMockItems : 0 // 使用设定的模拟总数
        };
        // data.total = data.list.length; // 移除这行，使用上面设定的 totalMockItems

        // 从本地存储读取并更新空闲桌数
        data.list = data.list.map(hall => {
          const savedTables = uni.getStorageSync(`tables_${hall.name}`);
          if (savedTables) {
            const availableCount = savedTables.filter(t => t.status === 'available').length;
            // 检查是否有用户预定但已过期的桌台，并将其状态恢复为空闲
            const reservedTableInfo = uni.getStorageSync(`reservedTable_${hall.name}`);
            if (reservedTableInfo) {
              const now = Date.now();
              if (now >= reservedTableInfo.expireTime) {
                const expiredTableIndex = savedTables.findIndex(t => t.id === reservedTableInfo.id);
                if (expiredTableIndex !== -1 && savedTables[expiredTableIndex].status === 'reserved') {
                  // 更新桌台状态为空闲
                  savedTables[expiredTableIndex].status = 'available';
                  // 移除过期的预订信息
                  uni.removeStorageSync(`reservedTable_${hall.name}`);
                  // 更新本地存储中的桌台信息
                  uni.setStorageSync(`tables_${hall.name}`, savedTables);
                  console.log(`[Index Page] Updated expired reservation for ${hall.name}, table ID ${reservedTableInfo.id} to available.`);
                  // 重新计算可用桌数
                  availableCount = savedTables.filter(t => t.status === 'available').length;
                }
              }
            }
            return { ...hall, availableTables: availableCount };
          } else {
            // 如果本地存储没有数据，则使用初始数据
            // 同时生成初始桌台状态并存入本地存储
            const initialTables = Array.from({length: hall.totalTables}, (_, i) => ({
              id: `${hall.id}_${i+1}`,
              number: `${i+1}号桌`,
              status: i < hall.availableTables ? 'available' : 'occupied'
            }));
            uni.setStorageSync(`tables_${hall.name}`, initialTables);
            return hall;
          }
        });

        this.poolHalls = this.currentPage === 1 
          ? data.list 
          : [...this.poolHalls, ...data.list]
        this.total = data.total // 使用从 data 获取的总数
        this.noMore = this.poolHalls.length >= this.total
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
        callback && callback()
      }
    },
    refreshHallDataFromStorage() {
      if (this.poolHalls.length === 0) return; // 如果还没有加载数据，则不执行

      let updated = false;
      this.poolHalls = this.poolHalls.map(hall => {
        const savedTables = uni.getStorageSync(`tables_${hall.name}`);
        if (savedTables) {
          let currentAvailableCount = hall.availableTables; // Start with current count
          // Check for expired reservations first
          const reservedTableInfo = uni.getStorageSync(`reservedTable_${hall.name}`);
          if (reservedTableInfo) {
            const now = Date.now();
            if (now >= reservedTableInfo.expireTime) {
              const expiredTableIndex = savedTables.findIndex(t => t.id === reservedTableInfo.id);
              if (expiredTableIndex !== -1 && savedTables[expiredTableIndex].status === 'reserved') {
                // Update table status to available
                savedTables[expiredTableIndex].status = 'available';
                // Remove expired reservation info
                uni.removeStorageSync(`reservedTable_${hall.name}`);
                // Update table info in local storage
                uni.setStorageSync(`tables_${hall.name}`, savedTables);
                console.log(`[Index Page - onShow] Updated expired reservation for ${hall.name}, table ID ${reservedTableInfo.id} to available.`);
                updated = true; // Mark as updated
              }
            }
          }
          
          // Recalculate available count *after* handling expired reservations
          const latestAvailableCount = savedTables.filter(t => t.status === 'available').length;

          // Only update if the count has changed
          if (hall.availableTables !== latestAvailableCount) {
             updated = true;
             return { ...hall, availableTables: latestAvailableCount };
          }
        }
        return hall; // Return original object if no update needed
      });

      // Force view update if any data changed
      if (updated) {
        this.$forceUpdate();
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
}
.search-bar {
  margin-bottom: 20rpx;
}
.search-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1px solid #ddd;
  border-radius: 40rpx;
}
.pool-hall-card {
  margin-bottom: 20rpx;
  padding: 20rpx;
  border: 1px solid #eee;
  border-radius: 10rpx;
}
.hall-image {
  height: 200rpx;
  width: 100%;
  border-radius: 10rpx;
  margin-bottom: 10rpx;
}
.hall-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}
.hall-address {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}
.hall-status {
  font-size: 28rpx;
  margin-bottom: 15rpx;
}
.status-dot {
  display: inline-block;
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  margin-right: 8rpx;
}
.status-dot.open {
  background-color: #07C160;
}
.status-dot.closed {
  background-color: #999;
}
.available {
  color: #07C160;
}
.full {
  color: #FF0000;
}
.action-buttons {
  display: flex;
  justify-content: space-between;
}
.nav-btn, .book-btn {
  width: 48%;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  border-radius: 35rpx;
  font-size: 28rpx;
}
.nav-btn {
  background-color: #F0F0F0;
  color: #333;
}
.book-btn {
  background-color: #07C160;
  color: #fff;
}
.no-more-data {
  text-align: center;
  color: #999;
  font-size: 24rpx;
  padding: 20rpx 0;
}
</style>